package com.elsa.auth.configure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.elsa.auth.service.ElsaUserDetailService;

/**
 * @projectName：elsa-auth
 * @typeName：ElsaSecurityConfigure
 * @author：cos
 * @date：2021年5月7日
 * @version
 * @desc：WebSecurity类型的安全配置类
 */
@Order(2)	// 增加过滤链的优先级，因为ElsaResourceServerConfigure的优先级为3
@EnableWebSecurity	// 开启和Web相关的安全配置
public class ElsaSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private ElsaUserDetailService userDetailService;

   @Autowired
   private PasswordEncoder passwordEncoder;
    
    // 一个相同的密码，每次加密出来的加密串都不同
    public static void main(String[] args) {
        String password = "123456";
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println(encoder.encode(password));
        System.out.println(encoder.encode(password));
    }
    
    //密码模式需要使用到这个Bean:AuthenticationManager
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/oauth/**")	//安全配置类只对/oauth/开头的请求有效
            .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").authenticated()
            .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder);
    }
}
